import { defineStore } from "pinia";
import { ref } from "vue";
import gsap from "gsap";

export const useGameStore = defineStore("game", () => {
  const snake = ref<{ x: number; y: number }[]>([]);
  const food = ref({ x: 0, y: 0 });
  const direction = ref("RIGHT");
  const gameOver = ref(false);
  const gameBoard = ref<HTMLElement | null>(null);
  const gameLoop = ref<number | null>(null);
  const speedLevel = ref(5); // 默认速度级别5
  const isPlaying = ref(false);
  const score = ref(0);

  const updateSpeed = (level: number) => {
    speedLevel.value = Math.min(10, Math.max(1, level));
    if (gameLoop.value) {
      clearInterval(gameLoop.value);
      gameLoop.value = setInterval(moveSnake, 220 - speedLevel.value * 20);
    }
  };

  const initGame = (board: HTMLElement) => {
    gameBoard.value = board;
    snake.value = [
      { x: 10, y: 10 },
      { x: 10, y: 11 },
      { x: 10, y: 12 },
    ];
    generateFood();
    renderGame();
  };

  const resetGame = () => {
    if (gameLoop.value) {
      clearInterval(gameLoop.value);
      gameLoop.value = null;
    }
    score.value = 0;
    gameOver.value = false;
    snake.value = [
      { x: 10, y: 10 },
      { x: 10, y: 11 },
      { x: 10, y: 12 },
    ];
    direction.value = "RIGHT";
    generateFood();
    renderGame();
    isPlaying.value = false;
  };

  const startGame = () => {
    resetGame();
    gameLoop.value = setInterval(moveSnake, 220 - speedLevel.value * 20);
    isPlaying.value = true;
  };

  const moveSnake = () => {
    if (gameOver.value) return;

    const head = { ...snake.value[0] };

    switch (direction.value) {
      case "UP":
        head.y -= 1;
        break;
      case "DOWN":
        head.y += 1;
        break;
      case "LEFT":
        head.x -= 1;
        break;
      case "RIGHT":
        head.x += 1;
        break;
    }

    // Check collisions
    if (
      head.x < 0 ||
      head.y < 0 ||
      !gameBoard.value ||
      head.x >= gameBoard.value.clientWidth / 20 ||
      head.y >= gameBoard.value.clientHeight / 20 ||
      snake.value.some((segment) => segment.x === head.x && segment.y === head.y)
    ) {
      gameOver.value = true;
      if (gameLoop.value) {
        clearInterval(gameLoop.value);
      }
      return;
    }

    // Check food
    if (head.x === food.value.x && head.y === food.value.y) {
      score.value += 1;
      generateFood();
    } else {
      snake.value.pop();
    }

    snake.value.unshift(head);
    renderGame();
  };

  const generateFood = () => {
    if (!gameBoard.value) return;

    const maxX = Math.floor(gameBoard.value.clientWidth / 20);
    const maxY = Math.floor(gameBoard.value.clientHeight / 20);

    let newFood: { x: number; y: number } | { x: number; y: number };
    do {
      newFood = {
        x: Math.floor(Math.random() * maxX),
        y: Math.floor(Math.random() * maxY),
      };
    } while (snake.value.some((segment) => segment.x === newFood.x && segment.y === newFood.y));

    food.value = newFood;

    // Add pulsing animation to new food
    const foodElement = document.createElement("div");
    foodElement.style.position = "absolute";
    foodElement.style.width = "20px";
    foodElement.style.height = "20px";
    foodElement.style.backgroundColor = "red";
    foodElement.style.left = `${newFood.x * 20}px`;
    foodElement.style.top = `${newFood.y * 20}px`;
    gameBoard.value?.appendChild(foodElement);

    gsap.to(foodElement, {
      scale: 1.2,
      duration: 0.5,
      repeat: -1,
      yoyo: true,
      ease: "sine.inOut",
    });
  };

  const renderGame = () => {
    if (!gameBoard.value) return;

    // Clear board
    gameBoard.value.innerHTML = "";

    // Render snake with GSAP animations
    snake.value.forEach((segment, index) => {
      const segmentElement = document.createElement("div");
      segmentElement.style.position = "absolute";
      segmentElement.style.width = "20px";
      segmentElement.style.height = "20px";
      segmentElement.style.backgroundColor = index === 0 ? "darkgreen" : "green";
      segmentElement.style.left = `${segment.x * 20}px`;
      segmentElement.style.top = `${segment.y * 20}px`;
      gameBoard.value?.appendChild(segmentElement);
    });

    // Render food (no animation here, it's already handled in generateFood)
    const foodElement = document.createElement("div");
    foodElement.style.position = "absolute";
    foodElement.style.width = "20px";
    foodElement.style.height = "20px";
    foodElement.style.backgroundColor = "red";
    foodElement.style.left = `${food.value.x * 20}px`;
    foodElement.style.top = `${food.value.y * 20}px`;
    gameBoard.value?.appendChild(foodElement);
  };

  const cleanup = () => {
    if (gameLoop.value) {
      clearInterval(gameLoop.value);
    }
  };

  return {
    snake,
    food,
    direction,
    gameOver,
    isPlaying,
    score,
    initGame,
    startGame,
    resetGame,
    cleanup,
    renderGame,
    updateSpeed,
  };
});
